//
//  PushCircleViewController.m
//  Lucky28
//
//  Created by zr on 2018/8/2.
//  Copyright © 2018年 zr. All rights reserved.
//

#import "PushCircleViewController.h"

@interface PushCircleViewController ()<UITextFieldDelegate,UITextViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
    
    UIImagePickerController *_imagePickerController;
}

@property (nonatomic, weak)UITextField * titleTextFiled;
@property (nonatomic, weak)UITextView * textView;
@property (nonatomic, weak)UIButton * pictureButton;
@property (nonatomic, strong)UIAlertController * alertVC;
@property (nonatomic, copy)NSString * images;

@end

@implementation PushCircleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    
    [self setupNav];
    [self setupUI];
    [self setupAlertVC];
}

- (void)setupNav{
    
    self.title = @"发帖子";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    [backButton setTitle:@"取消" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
    backButton.titleLabel.font = [UIFont boldSystemFontOfSize:15 * SCREENH6];
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
    
    UIButton * backButton1 = [[UIButton alloc] init];
    
    //    backButton.frame = CGRectMake(0 , 0 , 65 * SCREENH6, 20 * SCREENH6);
    [backButton1 setTitle:@"发表" forState:UIControlStateNormal];
    backButton1.titleLabel.font = [UIFont boldSystemFontOfSize:15 * SCREENH6];
    [backButton1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [backButton1 addTarget:self action:@selector(pushMessageInfo) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * nextButton = [[UIBarButtonItem alloc] initWithCustomView:backButton1];
    
    self.navigationItem.rightBarButtonItem = nextButton;
    
}

- (void)setupUI{
    
    UITextField * titleTextFiled = [[UITextField alloc] initWithFrame:CGRectMake(15 * SCREENH6, 15 * SCREENH6, SCREEN_WIDTH - 30 * SCREENH6, 40 * SCREENH6)];
    
    titleTextFiled.borderStyle = UITextBorderStyleRoundedRect;
    titleTextFiled.backgroundColor = ColorWithRGB(0xEDEDED);
    //设置光标颜色
    titleTextFiled.tintColor = [UIColor blackColor];
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0xD9D8D8);
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    titleTextFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请先输入一个标题" attributes:attrs];
    titleTextFiled.textColor = [UIColor blackColor];
    titleTextFiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    titleTextFiled.returnKeyType = UIReturnKeyDone;
    titleTextFiled.delegate = self;
    
    self.titleTextFiled = titleTextFiled;
    
    [self.view addSubview:self.titleTextFiled];
    
    
    // 创建textView
    UITextView *textView =[[UITextView alloc]initWithFrame:CGRectMake(15 * SCREENH6,80 * SCREENH6,SCREEN_WIDTH - 30 * SCREENH6,160 * SCREENH6)];
    textView.backgroundColor= [UIColor whiteColor];
    textView.text = @"请输入帖子内容";
    textView.font = [UIFont systemFontOfSize:15 * SCREENH6];
    textView.textColor = [UIColor blackColor];//ColorWithRGB(0xEDEDED);
    textView.layer.borderWidth = 2.0f;
    textView.layer.borderColor = [ColorWithRGB(0xe7e7e7) CGColor];
    textView.delegate = self;
    
    self.textView = textView;
    
    [self.view addSubview:self.textView];
    
    
    UIButton * pictureButton = [[UIButton alloc]initWithFrame:CGRectMake(15 * SCREENH6,260 * SCREENH6,SCREEN_WIDTH - 30 * SCREENH6,215 * SCREENH6)];
    
    [pictureButton setImage:ImageNamed(@"shangchuan") forState:UIControlStateNormal];
    [pictureButton addTarget:self action:@selector(ClickPictureButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.pictureButton = pictureButton;
    
    [self.view addSubview:self.pictureButton];
    
}


- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo

{
    
    [self.pictureButton setImage:image forState:UIControlStateNormal];
    
//    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
//
//    {
//        //图片存入相册
//
//        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
//
//    }
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString * token = [userDefaults objectForKey:@"token"];
    
    NSData *frontImageData = UIImageJPEGRepresentation(image,0.5);

    
    NSDictionary * dic = @{@"files":frontImageData,@"token":token};
    
    [[NetworkTool sharedTools] POST:@"/index/Note/noteupload" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat  = @"yyyyMMddHHmmss";
        NSString *str  = [formatter stringFromDate:[NSDate date]];
        NSString *fileName  = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:frontImageData name:@"files" fileName:fileName mimeType:@"image/png"];
        
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
      
        
        NSInteger code = [responseObject[@"status"] integerValue];
        
        if (code == 200){
            
            self.images = [NSString stringWithFormat:@"%@",responseObject[@"data"]];
        }else{

        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

//进入拍摄页面点击取消按钮

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}



- (void)pushMessageInfo{
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString * token = [userDefaults objectForKey:@"token"];
    
    NSDictionary * dict = @{@"title":self.titleTextFiled.text,@"token":token,@"content":self.textView.text,@"type":@"4",@"images":self.images};
    
    [[NetworkTool sharedTools] POST:@"/index/Note/add" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        NSLog(@"==%@",responseObject);
        
        int status = [responseObject[@"status"] intValue];
        
        if (status == 200) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}


- (void)ClickPictureButton{
    
    [self presentViewController:self.alertVC animated:YES completion:nil];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if(textView.text.length < 1){
        textView.text = @"请输入帖子内容";
        textView.textColor = [UIColor grayColor];
    }else{
        
        [self.textView resignFirstResponder];
    }
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if([textView.text isEqualToString:@"请输入帖子内容"]){
        textView.text=@"";
        textView.textColor=[UIColor blackColor];
    }
}


//实现UITextField代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];//取消第一响应者
    
    return YES;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.titleTextFiled resignFirstResponder];
    [self.textView resignFirstResponder];
}


- (void)backToView{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
